<template>
  <div class="app-container" id="newSport">
    <el-form ref="form" :model="form" label-width="80px" :rules="addRules">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入运动标题" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <div class="block">
          <el-cascader expand-trigger="hover" :options="typeOptions" v-model="sportType" @change="handleChange">
          </el-cascader>
        </div>
      </el-form-item>
      <el-form-item label="标签">
        <el-tag :key="tag.id" v-for="tag in form.tags" :closable="true" :close-transition="false" @close="handleClose(tag)" style="margin-left:10px;">
          {{tag.tag}}
        </el-tag>
        <el-input class="input-new-tag" v-if="tagVisible" v-model="tagValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleTagConfirm"
          @blur="handleTagConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showTag">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="发起人">
        <el-input v-model="form.originator" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="人数">
        <el-input-number v-model="form.number" :controls="false"></el-input-number>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.describe" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="地点">
        <el-button @click="dialogTableVisible = true">{{address}}</el-button>
      </el-form-item>
      <el-dialog title="选择地址" :visible.sync="dialogTableVisible" top="15vh">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap" :center="center" :zoom="zoom" :plugin="plugin" class="amap-demo" :events="events">
            <el-amap-marker :position="MakerPosition"></el-amap-marker>
          </el-amap>
          <div class="toolbar">
            <br /> 地址：{{ address }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      </span>
      </el-dialog>
      <el-form-item label="封面海报">
        <el-tabs v-model="changeImg"  class="w500">
          <el-tab-pane label="封面图" name="first">
            <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="coverImageUrl" :src="coverImageUrl" class="cover">
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
              </el-upload>
          </el-tab-pane>
          <el-tab-pane label="海报图" name="second">
            <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload">
              <img v-if="coverImageUrl2" :src="coverImageUrl2" class="cover">
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
              </el-upload>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker v-model="form.time" type="datetime" placeholder="选择日期" format="yyyy-MM-dd HH:mm" :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="详情">
        <div class="changeText">HTML模式
          <el-switch v-model="openCode" on-text="" off-text="">
          </el-switch>
        </div>
        <el-input v-if="openCode==true" type="textarea" v-model="form.content" class="w500"></el-input>
        <quill-editor class="w500" v-else ref="myTextEditor" v-model="form.content" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @ready="onEditorReady($event)">
          </quill-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即发布</el-button>
        <el-button type="warning" @click="onSave">存为草稿</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="提示" :visible.sync="dialogAddressVisible" size="tiny">
      <span>请选择运动地点</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAddressVisible = false">取消</el-button>
    <el-button  @click="dialogAddressVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogSuccessVisible" size="tiny">
      <span>添加成功,是否跳转到首页？</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogSuccessVisible = false">取消</el-button>
    <el-button  @click="GoToIndex" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogAvatarVisible" size="tiny">
      <span>请选择完善运动信息</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAvatarVisible = false">取消</el-button>
    <el-button  @click="dialogAvatarVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
import dateFormat from "@/utils/date";
import { isvalidStrategyContent } from "@/utils/validate";
import { getToken } from "@/utils/auth";
import { getSportById, delSportTag, addSportTag, addSport } from "@/api/sport";
export default {
  data() {
    let self = this;
    const validateTitle = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入正确的标题"));
      } else {
        callback();
      }
    };
    const validateDesc = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入描述"));
      } else {
        callback();
      }
    };
    const validateContent = (rule, value, callback) => {
      if (!isvalidStrategyContent(value)) {
        callback(new Error("请输入内容"));
      } else {
        callback();
      }
    };
    return {
      tagValue: "",
      tagVisible: false,
      dialogSuccessVisible: false,
      dialogAddressVisible: false,
      dialogAvatarVisible: false,
      dialogTableVisible: false,
      changeImg: "first",
      sportType: [],
      zoom: 12,
      center: [121.59996, 31.197646],
      address: "选择地址",
      describe: "",
      adcode: "",
      position: "",
      searchOption: {
        city: "全国",
        citylimit: true
      },
      plugin: [
        {
          pName: "Geolocation",
          events: {
            init(o) {
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  console.log(result);
                  self.addressInfo.lng = result.position.lng;
                  self.addressInfo.lat = result.position.lat;
                  self.addressInfo.township = result.addressComponent.township;
                  self.addressInfo.traffic = result.formattedAddress;
                  self.address = result.formattedAddress;
                  self.addressInfo.adcode = result.addressComponent.adcode;
                  self.addressInfo.position =
                    result.addressComponent.city +
                    "-" +
                    result.addressComponent.district;
                }
              });
            }
          }
        }
      ],
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.addressInfo.lng = lng;
          self.addressInfo.lat = lat;
          self.MakerPosition = [e.lnglat.lng, e.lnglat.lat];
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                self.addressInfo.traffic = result.regeocode.formattedAddress;
                self.addressInfo.township =
                  result.regeocode.addressComponent.township;
                self.address = result.regeocode.formattedAddress;
                self.addressInfo.adcode =
                  result.regeocode.addressComponent.adcode;
                self.addressInfo.position =
                  result.regeocode.addressComponent.city +
                  "-" +
                  result.regeocode.addressComponent.district;
                self.$nextTick();
              }
            }
          });
        }
      },
      MakerPosition: [121.59996, 31.197646],
      lng: 0,
      lat: 0,
      openCode: false,
      startSellTime: "",
      endSellTime: "",
      typeOptions: [
        {
          value: "pe",
          label: "体育运动",
          children: [
            {
              value: "basketball",
              label: "篮球"
            },
            {
              value: "footBall",
              label: "足球"
            },
            {
              value: "badminton",
              label: "羽毛球"
            },
            {
              value: "skip",
              label: "骑行"
            },
            {
              value: "else",
              label: "其他"
            }
          ]
        },
        {
          value: "fallow",
          label: "休闲运动",
          children: [
            {
              value: "moutain",
              label: "登山"
            },
            {
              value: "run",
              label: "跑步"
            },
            {
              value: "skidding",
              label: "轮滑"
            },
            {
              value: "else",
              label: "其他"
            }
          ]
        },
        {
          value: "maxi",
          label: "极限运动",
          children: [
            {
              value: "marathon",
              label: "马拉松"
            },
            {
              value: "cross",
              label: "越野"
            },
            {
              value: "else",
              label: "其他"
            }
          ]
        }
      ],
      form: {
        u_id: "",
        title: "",
        type: "",
        describe: "",
        time: "",
        number: "",
        content: "<p>请输入活动内容...</p>",
        cover: "",
        imgurl: "",
        tags: []
      },
      addressInfo: {
        lat: "",
        lng: "",
        position: "",
        traffic: "",
        adcode: "",
        township: ""
      },
      coverImageUrl: "",
      coverImageUrl2: "",
      addRules: {
        name: [{ required: true, trigger: "blur", validator: validateTitle }],
        describe: [
          { required: true, trigger: "blur", validator: validateDesc }
        ],
        content: [
          { required: true, trigger: "blur", validator: validateContent }
        ]
      },
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ script: "sub" }, { script: "super" }],
            [{ indent: "-1" }, { indent: "+1" }],
            [{ direction: "rtl" }],
            [{ size: ["small", false, "large", "huge"] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ font: [] }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ["clean"],
            ["image"]
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      sport_id: 0,
      status: 1
    };
  },
  created() {
    let id = this.$route.query.id;

    if (id) {
      this.sport_id = id;
      getSportById(id).then(res => {
        if (res.message == "ok") {
          this.form.title = res.sport.title;
          this.u_id = res.sport.u_id;
          this.form.cover = res.sport.cover;
          this.form.imgurl = res.sport.imgurl;
          this.form.number = res.sport.number;
          this.form.describe = res.sport.describe;
          this.coverImageUrl = res.sport.cover;
          this.coverImageUrl2 = res.sport.imgurl;
          this.form.time = res.sport.time;
          if (res.detail) {
            this.form.content = res.detail.content;
          }

          this.form.type = res.sport.type;
          this.form.childType = res.sport.childType;
          this.form.tags = res.tags;
          this.form.originator = res.sport.originator;
          this.addressInfo.lat = res.sport.lat;
          this.addressInfo.lng = res.sport.lng;
          this.addressInfo.position = res.sport.address;
          this.addressInfo.adcode = res.sport.city;
          this.addressInfo.township = res.sport.district;
          this.addressInfo.traffic = res.sport.traffic;
          if (res.sport.traffic) {
            this.address = res.sport.traffic;
          }
          this.sportType = [this.form.type, this.form.childType];
        }
      });
    } else {
      this.u_id = getToken();
    }
  },
  methods: {
    onEditorBlur(editor) {
      // console.log('editor blur!', editor)
    },
    onEditorFocus(editor) {
      // console.log('editor focus!', editor)
    },
    onEditorReady(editor) {
      // console.log('editor ready!', editor)
    },
    handleClose(tag) {
      if (this.sport_id != 0) {
        delSportTag(tag.id).then(res => {
          if (res.message == "ok") {
            this.form.tags.splice(this.form.tags.indexOf(tag), 1);
            this.$message({
              message: "标签已删除",
              type: "success"
            });
            this.tagValue = "";
          }
        });
      } else {
        this.form.tags.splice(this.form.tags.indexOf(tag), 1);
        this.$message({
          message: "标签已删除",
          type: "success"
        });
        this.tagValue = "";
      }
    },
    onSave() {
      this.status = 0;
      this.onSubmit();
    },
    pickerOptions0: {
      disabledDate(time) {
        return time.getTime() < Date.now() - 8.64e7;
      }
    },
    onSubmit() {
      if (this.address == "选择地址") {
        this.dialogAddressVisible = true;
        return;
      }

      if (
        this.form.title == "" ||
        this.form.type == "" ||
        this.form.content == "" ||
        this.form.time == "" ||
        this.form.imgurl == "" ||
        this.form.cover == ""
      ) {
        this.dialogAvatarVisible = true;
        return;
      }

      this.form.u_id = this.u_id;
      this.form.sport_id = this.sport_id * 1;
      this.form.status = this.status;
      let forDate = new Date(this.form.time).getTime();
      this.form.time = dateFormat(new Date(forDate * 1), "yyyy-MM-dd");
      console.log(this.form);
      addSport(this.form, this.addressInfo).then(res => {
        if (res.message == "success") {
          if (this.sport_id == 0) {
            this.form.tags.map((tag, index) => {
              addSportTag(res.sport_id, tag.tag).then(resTag => {
                if (
                  resTag.message == "ok" &&
                  index == this.form.tags.length - 1
                ) {
                  this.$message({
                    message: "活动已添加",
                    type: "success"
                  });
                  this.$router.push({ path: "/sport/index" });
                }
              });
            });
          } else {
            this.$message({
              message: "活动已更新",
              type: "success"
            });
            this.$router.push({ path: "/sport/index" });
          }
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    GoToIndex() {
      this.$router.push({ path: "/" });
    },
    handlePreview(file) {
      console.log(file);
    },
    handleAvatarSuccess(res, file) {
      this.coverImageUrl = URL.createObjectURL(file.raw);
      this.form.cover = "http://" + res.data.url;
      this.$message({
        message: "上传成功",
        type: "success"
      });
    },
    handleAvatarSuccess2(res, file) {
      this.coverImageUrl2 = URL.createObjectURL(file.raw);
      this.form.imgurl = "http://" + res.data.url;
      this.$message({
        message: "上传成功",
        type: "success"
      });
    },
    beforeAvatarUpload(file) {
      this.$message("正在上传...");
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传封面图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    addMarker: function() {
      let lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
      let lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
      this.MakerPosition = [lng, lat];
    },
    onSearchResult(pois) {
      var self = this;
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.MakerPosition = [poi.lng, poi.lat];
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([poi.lng, poi.lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                self.addressInfo.traffic = result.regeocode.formattedAddress;
                self.addressInfo.township =
                  result.regeocode.addressComponent.township;
                self.addressInfo.lat = poi.lat;
                self.addressInfo.lng = poi.lng;
                self.addressInfo.adcode =
                  result.regeocode.addressComponent.adcode;
                self.addressInfo.position =
                  result.regeocode.addressComponent.city +
                  "-" +
                  result.regeocode.addressComponent.district;
                self.address = result.regeocode.formattedAddress;
                self.$nextTick();
              }
            }
          });
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.center = [center.lng, center.lat];
      }
    },
    showTag() {
      this.tagVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleTagConfirm() {
      this.tagVisible = false;
      if (this.tagValue.trim() == "") {
        return;
      }

      let tagValue = this.tagValue;
      let id = 0;
      if (this.sport_id != 0) {
        addSportTag(this.sport_id, tagValue).then(res => {
          if (res.message == "ok") {
            id = res.id;
            this.$message({
              message: "添加标签成功",
              type: "success"
            });

            this.form.tags.push({ tag: tagValue, id });

            this.tagValue = "";
          }
        });
      } else {
        this.form.tags.push({ tag: tagValue });
      }
    },
    handleChange(value) {
      this.form.type = value[0];
      this.form.childType = value[1];
    }
  }
};
</script>
<style>
.amap-demo {
  height: 300px;
}

.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}

#newStrategy .el-vue-search-box-container {
  position: absolute;
}

.amap-page-container {
  position: relative;
  height: 360px;
}

.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.cover {
  width: 178px;
  height: 178px;
  display: block;
}
.w500 {
  width: 500px;
}
</style>